from django.contrib import admin
from .models import SystemLog
from django.utils.html import format_html 

# Register your models here.
@admin.register(SystemLog) #帮你把 SystemLog 模型注册进后台管理，并绑定到这个 SystemLogAdmin 管理类。
class SystemLogAdmin(admin.ModelAdmin):
    # 在后台列表页显示的字段
    list_display = (
        'create_time', 'level', 'method', 'path', 'status_code', 'colored_duration',  'ip_address', 'username'
    )
    
    #右侧的过滤选项
    list_filter = ('level', 'status_code', 'username', 'create_time')
    # 搜索框可以搜索的字段
    search_fields = ('message', 'path', 'ip_address', 'username', 'user_agent')
    # 按创建时间降序排列
    ordering = ('-create_time',)
    # 每页显示多少条记录
    list_per_page = 50
    # 只读字段，防止在后台被修改
    readonly_fields = (
        'level', 'message', 'method', 'path', 'status_code', 
        'duration', 'ip_address', 'user_agent', 'username', 'create_time')
    
    # ✅ 定义自定义显示列
    def colored_duration(self, obj):
    
        if obj.duration in (None, ""):
            return "-"

        # 1) 尽量转成 float；失败就原样显示
        try:
            duration = float(obj.duration)
        except (TypeError, ValueError):
            return str(obj.duration)

        # 2) 选择颜色
        if duration > 3:
            color = "red"
        elif duration > 1:
            color = "orange"
        else:
            color = "green"

        # 3) 先在 Python 里把数字格式化成字符串，再交给 format_html
        formatted = f"{duration:.3f}s"
        return format_html('<span style="color:{};">{}</span>', color, formatted)

    colored_duration.short_description = "耗时"
